package com.example.idlefish.HomeAndSearch

import NavAdapter
import SearchHistoryManager
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import android.widget.ViewFlipper
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.GoodsInfo.pojo.Class_t
import com.example.idlefish.GoodsInfo.pojo.Classification
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import org.json.JSONArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.concurrent.thread

class HomeMainFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.home_main, container, false)
    }

    val goodContentLauncher = registerForActivityResult(GooddResultContract()){
            result->
        if(result)
        {
            Toast.makeText(context, "成功从详情页返回", Toast.LENGTH_LONG).show()
        }
        else{
            Toast.makeText(context, "详情页返回失败", Toast.LENGTH_LONG).show()
        }
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val RecycleGoods1 = view.findViewById<RecyclerView>(R.id.RecycleGoods1)
        val RecycleGoods2 = view.findViewById<RecyclerView>(R.id.RecycleGoods2)
        val productList: MutableList<ProductInfo> = mutableListOf()
        val recyclerView = view.findViewById<RecyclerView>(R.id.RecyclerView)
        val changeButton = view.findViewById<TextView>(R.id.changeButton)
        val search_button = view.findViewById<TextView>(R.id.search_button)
        val text1 = view.findViewById<TextView>(R.id.text1)
        val text2 = view.findViewById<TextView>(R.id.text2)
        val text3 = view.findViewById<TextView>(R.id.text3)
        val text4 = view.findViewById<TextView>(R.id.text4)

        val targetTextView = view.findViewById<TextView>(R.id.targetTextView)



        RecycleGoods1.setHasFixedSize(true)
        // 设置布局管理器
        RecycleGoods1.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        RecycleGoods2.setHasFixedSize(true)
        // 设置布局管理器
        RecycleGoods2.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

        val viewFlipper = view.findViewById<ViewFlipper>(R.id.viewFlipper)
        viewFlipper.startFlipping()
        viewFlipper.setOnClickListener {
            val intent = Intent(context, SearchActivity::class.java)
            startActivity(intent)
        }
        search_button.setOnClickListener{

            val currentView = viewFlipper.currentView
            if (currentView is TextView) {

                val currentText = currentView.text.toString()
                val intent = Intent(requireContext(), OneResultActivity::class.java)
                intent.putExtra("name", currentText) // 传入键值对
                intent.putExtra("type", "1")
                startActivity(intent)
                val searchHistoryManager = SearchHistoryManager(requireContext())
                // 添加搜索记录
                searchHistoryManager.saveSearchRecord(currentText)

            }
        }



        var temp = 0
        val ClassList = mutableListOf<Class_t>()
        recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

        Thread {
            try {
                val urlString = "${NetworkSettings.HTTP}/product/getclass"
                val url = URL(urlString)
                val conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"

                val reader = BufferedReader(InputStreamReader(conn.inputStream), 8192)
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                reader.close()
                val jsonArray = JSONArray(response.toString())
                for (i in 0 until jsonArray.length()) {
                    val obj = jsonArray.getJSONObject(i)
                    val id = obj.getInt("id")
                    val name = obj.getString("name")
                    ClassList.add(
                        Class_t(
                            id = id,
                            name = name
                        )
                    )
                }
                println(ClassList + "666\n")
                requireActivity().runOnUiThread {
                    val adapter = NavAdapter(ClassList.take(15), { selectedItem ->
                        println("Clicked item: $selectedItem")
                        changeButton.text = "▼"
                        temp = selectedItem
                        getlist(productList, RecycleGoods1,RecycleGoods2,temp, targetTextView);
                    }, recyclerView)
                    recyclerView.adapter = adapter

                    val randomFour = ClassList.shuffled().take(4)
                    text1.text = randomFour[0].name
                    text2.text = randomFour[1].name
                    text3.text = randomFour[2].name
                    text4.text = randomFour[3].name


                }

            } catch (e: Exception) {
                Log.e("Product", "Exception occurred: ${e.message}", e)
            }

        }.start()
        getlist(productList, RecycleGoods1,RecycleGoods2,temp, targetTextView);
        changeButton.setOnClickListener {
            if (changeButton.text == "▼") {
                recyclerView.layoutManager = GridLayoutManager(activity, 3)
                changeButton.text = "▲"
            } else {
                changeButton.text = "▼"
                recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
                scrollToCenter(view, temp)
            }
            recyclerView.adapter!!.notifyDataSetChanged()
        }



    }

    var isSyncing = false


    fun setupSyncedRecyclerViews(recyclerView1: RecyclerView, recyclerView2: RecyclerView) {
        // Variable to prevent infinite loop
        var isSyncing = false

        // Scroll listener to handle sync
        val scrollListener = object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (isSyncing) return
                isSyncing = true

                if (recyclerView === recyclerView1) {
                    syncScroll(recyclerView1, recyclerView2)
                } else if (recyclerView === recyclerView2) {
                    syncScroll(recyclerView2, recyclerView1)
                }

                isSyncing = false
            }
        }

        // Add the scroll listener to both RecyclerViews
        recyclerView1.addOnScrollListener(scrollListener)
        recyclerView2.addOnScrollListener(scrollListener)
    }

    // Helper function to sync scroll offset
    private fun syncScroll(source: RecyclerView, target: RecyclerView) {
        val sourceLayoutManager = source.layoutManager as? LinearLayoutManager ?: return
        val targetLayoutManager = target.layoutManager as? LinearLayoutManager ?: return

        // Get the first visible item's position and offset in the source RecyclerView
        val firstVisiblePosition = sourceLayoutManager.findFirstVisibleItemPosition()
        val firstVisibleView = sourceLayoutManager.findViewByPosition(firstVisiblePosition) ?: return
        val offset = firstVisibleView.top - source.paddingTop

        // Scroll the target RecyclerView to the same position and offset
        targetLayoutManager.scrollToPositionWithOffset(firstVisiblePosition, offset)
    }

    fun scrollToCenter(view: View, position: Int) {
        val recyclerView = view.findViewById<RecyclerView>(R.id.RecyclerView)
        val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return

        recyclerView.post {
            // 等待 RecyclerView 完全布局
            recyclerView.addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
                override fun onLayoutChange(
                    v: View?, left: Int, top: Int, right: Int, bottom: Int,
                    oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int
                ) {
                    recyclerView.removeOnLayoutChangeListener(this) // 移除监听器

                    val targetView = layoutManager.findViewByPosition(position)
                    val recyclerViewWidth = recyclerView.width

                    if (targetView != null) {
                        val itemWidth = targetView.width
                        val offset = (recyclerViewWidth / 2) - (itemWidth / 2)
                        layoutManager.scrollToPositionWithOffset(position, offset)
                    } else {
                        // 确保平滑滚动后偏移居中
                        recyclerView.smoothScrollToPosition(position)
                        recyclerView.post {
                            val newTargetView = layoutManager.findViewByPosition(position)
                            if (newTargetView != null) {
                                val itemWidth = newTargetView.width
                                val offset = (recyclerView.width / 2) - (itemWidth / 2)
                                layoutManager.scrollToPositionWithOffset(position, offset)
                            }
                        }
                    }
                }
            })

            // 强制布局更新
            recyclerView.requestLayout()
        }
    }
    fun getlist(productList:MutableList<ProductInfo>,
                RecycleGoods1:RecyclerView,
                RecycleGoods2:RecyclerView,
                temp:Int,
                targetTextView: TextView)
    {
        Thread {
            try {
                val urlString = "${NetworkSettings.HTTP}/product/getAll?kind=${temp+1}"
                val url = URL(urlString)
                val conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"

                val reader = BufferedReader(InputStreamReader(conn.inputStream), 8192)
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                reader.close()
                productList.clear()



                val jsonArray = JSONArray(response.toString())
                for (i in 0 until jsonArray.length()) {
                    val obj = jsonArray.getJSONObject(i)
                    val id = obj.getInt("id")
                    val name = obj.getString("name")
                    val info = obj.getString("text")
                    val address = obj.getString("address")
                    val price = obj.getDouble("price")
                    val wanting = obj.getInt("wanting")
                    val cut = obj.getInt("cut")
                    val advantage = obj.getString("advantage")
                    productList.add(
                        ProductInfo(
                            id = id,
                            name = name,
                            text = info,
                            price = price,
                            wanting = wanting,
                            advantage = advantage,
                            address = address,
                            cut = cut
                        )
                    )
                }

                // 在主线程中更新 UI
                requireActivity().runOnUiThread {
                    if(productList.size == 0)
                    {
                        targetTextView.visibility = View.VISIBLE // 数据为0，显示TextView
                    }
                    else{
                        targetTextView.visibility = View.GONE // 数据不为0，隐藏TextView
                    }
                    val (firstList, secondList) = if (productList.size < 4) {
                        // 如果 productList 的大小小于 4，直接不拆分
                        val middle = productList.size / 2
                        Pair(
                            CopyOnWriteArrayList(productList.subList(0, middle)),
                            CopyOnWriteArrayList(productList.subList(middle, productList.size))
                        )
                    } else {
                        // 如果 productList 的大小大于等于 4，执行拆分并处理奇数情况
                        val adjustedSize = if (productList.size % 2 != 0) productList.size - 1 else productList.size
                        val middle = adjustedSize / 2
                        Pair(
                            CopyOnWriteArrayList(productList.subList(0, middle)),
                            CopyOnWriteArrayList(productList.subList(middle, adjustedSize))
                        )
                    }

                    val adapter1 = GoodsAdapater(secondList, { itemId ->
                        goodContentLauncher.launch(itemId.toLong())
                    }, RecycleGoods1)
                    RecycleGoods1.adapter = adapter1

                    val adapter2 = GoodsAdapater(firstList, { itemId ->
                        println("Clicked item: $itemId")
                        goodContentLauncher.launch(itemId.toLong())
                    }, RecycleGoods2)
                    RecycleGoods2.adapter = adapter2
                    setupSyncedRecyclerViews(RecycleGoods1, RecycleGoods2)

                }

            } catch (e: Exception) {
                Log.e("Product", "Exception occurred: ${e.message}", e)
            }
        }.start()
    }

}